<?php

namespace app\admin\controller;

use app\admin\model\system\SystemAdmin;
use app\admin\model\system\SystemWxapp;
use services\UtilService;
use think\facade\Session;
use think\facade\Route as Url;

/**
 * @title 登录验证控制器
 * Class Login
 * @package app\admin\controller
 */
class Login extends SystemBasic
{
    /**
     * @api {get} admin/login/index [登录的入口地址]
     * @apiParam {string} [name] 名称
     * @apiParam {string} [pwd] 密码
     * @apiParam {string} [ver] 验证码
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 登录验证 + 验证码验证
     */
    public function verify()
    {
        if (!request()->isPost()) return $this->failed("请登录");
        list($account, $pwd, $verify) = UtilService::getMore([
            "account", "pwd", "verify"
        ], null, true);

        // if (!captcha_check($verify)) return $this->failed("验证码错误，请重新输入");
        $error = Session::get("login_err") ?: ["num" => 0, "time" => time()];
        if ($error["num"] >=5 && $error["time"] > strtotime("-5 minutes"))
            return $this->failed("错误次数过多，请稍后再试");
        // 验证账号以及密码
        $res = SystemAdmin::login($account, $pwd);
        if ($res) {
            Session::set("login_error", null);
            Session::save();
            // 綁定基类属性
            return $this->successful(["url" => Url::buildUrl("index/index")->build()]);
        }else{
            $error["num"] += 1;
            $error["time"] = time();
            Session::set("login_error", $error);
            Session::save();
            return $this->failed(SystemAdmin::getErrorInfo("用戶名或者密碼錯誤，請重新輸入"));
        }
    }

    /**
     * @title 验证码的获取
     * @return \think\Response
     */
    public function captcha()
    {
        ob_clean();
        return captcha();
    }

    /**
     * @title 退出登录；清除session
     */
    public function logout()
    {
        SystemAdmin::clearLoginInfo();
        $this->redirect(Url::buildUrl("index/index")->build());
    }
}